package config

import (
	"fmt"
	"os"
	"time"

	"gopkg.in/yaml.v3"
)

// Config 主配置结构体
type Config struct {
	GRPC     GRPCConfig       `yaml:"grpc"`
	Database DatabaseConfig   `yaml:"database"`
	Logging  LoggingConfig    `yaml:"logging"`
	Features FeatureConfig    `yaml:"features"`
	Servers  []TTServerConfig `yaml:"servers"`
}

type TTServerConfig struct {
	Description string `yaml:"description"`
	IP          string `yaml:"IP"`
	Port        string `yaml:"port"`
	Username    string `yaml:"username"`
	Password    string `yaml:"password"`
	DbType      string `yaml:"dbtype"`
}

// GRPCConfig gRPC 相关配置
type GRPCConfig struct {
	Server ServerConfig `yaml:"server"`
	Client ClientConfig `yaml:"client"`
}

type ServerConfig struct {
	Host              string        `yaml:"host"`
	Port              int           `yaml:"port"`
	MaxConnectionIdle time.Duration `yaml:"max_connection_idle"`
	Timeout           time.Duration `yaml:"timeout"`
	Description       string        `yaml:"description"`
}

type ClientConfig struct {
	Target  string        `yaml:"target"`
	Timeout time.Duration `yaml:"timeout"`
	Retry   RetryConfig   `yaml:"retry"`
}

type RetryConfig struct {
	MaxAttempts       int     `yaml:"max_attempts"`
	BackoffMultiplier float64 `yaml:"backoff_multiplier"`
}

// DatabaseConfig 数据库配置
type DatabaseConfig struct {
	Host     string     `yaml:"host"`
	Port     int        `yaml:"port"`
	Username string     `yaml:"username"`
	Password string     `yaml:"password"`
	Name     string     `yaml:"name"`
	Pool     PoolConfig `yaml:"pool"`
}

type PoolConfig struct {
	MaxConnections     int           `yaml:"max_connections"`
	MaxIdleConnections int           `yaml:"max_idle_connections"`
	ConnectionLifetime time.Duration `yaml:"connection_lifetime"`
}

// LoggingConfig 日志配置
type LoggingConfig struct {
	Level  string `yaml:"level"`
	Format string `yaml:"format"`
	Output string `yaml:"output"`
}

// FeatureConfig 功能开关配置
type FeatureConfig struct {
	EnableTLS     bool `yaml:"enable_tls"`
	EnableMetrics bool `yaml:"enable_metrics"`
	EnableTracing bool `yaml:"enable_tracing"`
}

// LoadConfig 加载 YAML 配置文件
func LoadConfig(filename string) (*Config, error) {
	data, err := os.ReadFile(filename)
	if err != nil {
		return nil, fmt.Errorf("读取配置文件失败: %w", err)
	}

	var config Config
	if err := yaml.Unmarshal(data, &config); err != nil {
		return nil, fmt.Errorf("解析 YAML 配置失败: %w", err)
	}

	return &config, nil
}

// GetServerAddress 获取 gRPC 服务器地址
func (c *Config) GetServerAddress() string {
	return fmt.Sprintf("%s:%d", c.GRPC.Server.Host, c.GRPC.Server.Port)
}

// Validate 配置验证
func (c *Config) Validate() error {
	if c.GRPC.Server.Port <= 0 || c.GRPC.Server.Port > 65535 {
		return fmt.Errorf("无效的端口号: %d", c.GRPC.Server.Port)
	}

	if c.GRPC.Client.Target == "" {
		return fmt.Errorf("客户端目标地址不能为空")
	}

	return nil
}
